//src/api/bondApi.js

/**
 * 本文件定义了与债券行情相关的所有前端 API 调用
 */

import http from '../utils/http';  // 你已有的 axios 实例，自动带 baseURL + token 拦截
import axios from 'axios';

/**
 * 获取债券列表
 */
export async function $fetchBondList() {
    const res = await axios.get('/api/bond/list');
    let body = res.data;
    console.log('响应数据:', body);
    
    // 如果 backend 将整个 body 当字符串返回
    if (typeof body === 'string') {
        const cleaned = body.replace(/\bNaN\b/g, 'null');
        try {
            body = JSON.parse(cleaned);
        } catch (e) {
            throw new Error(`响应非 JSON 格式：${cleaned}`);
        }
    }
    
    // 如果 body.data 是字符串，也需要 parse
    if (body && typeof body === 'object' && typeof body.data === 'string') {
        const cleanedData = body.data.replace(/\bNaN\b/g, 'null');
        try {
            body.data = JSON.parse(cleanedData);
        } catch (e) {
            throw new Error(`data 字段非 JSON 格式：${cleanedData}`);
        }
    }
    
    // 兼容纯数组或 { code, data } 对象
    if (Array.isArray(body)) {
        return body;
    }
    if (body && typeof body === 'object' && typeof body.code !== 'undefined') {
        if (body.code === 0 && Array.isArray(body.data)) {
            return body.data;
        }
        throw new Error(`业务异常：code=${body.code}, msg=${body.msg || '无'}`);
    }
    
    throw new Error(`返回格式不符合预期：${JSON.stringify(body)}`);
}

export async function $fetchBondTrend(symbol) {
    const res = await axios.get('/api/bond/trend', { params: { symbol } 
    }).then(res=>res.data);
    let body = res;
    console.log('响应数据:', body);
    
    // 如果 backend 将整个 body 当字符串返回
if (typeof body === 'string') {
    const cleaned = body.replace(/\bNaN\b/g, 'null')
    try {
      body = JSON.parse(cleaned)
    } catch (e) {
      throw new Error(`响应非 JSON 格式：${cleaned}`)
    }
  }
  
  // 如果 body.data 是字符串，也需要 parse
  if (body && typeof body === 'object' && typeof body.data === 'string') {
    const cleanedData = body.data.replace(/\bNaN\b/g, 'null')
    try {
      body.data = JSON.parse(cleanedData)
    } catch (e) {
      throw new Error(`data 字段非 JSON 格式：${cleanedData}`)
    }
  }
  
  
  
  // 兼容纯数组或 { code, data } 对象
  if (Array.isArray(body)) {
    return body
  }
  if (body && typeof body === 'object' && typeof body.code !== 'undefined') {
    if (body.code === 0 && Array.isArray(body.data)) {
      return body.data
    }
    throw new Error(`业务异常：code=${body.code}, msg=${body.msg || '无'}`)
  }
  
  throw new Error(`返回格式不符合预期：${JSON.stringify(body)}`)
    
}
/**
 * 购买债券
 * @param {Object} data - 购买数据
 * @returns {Promise<Object>}
 */
export const $buyBond = async (data) => {
    try {
        const response = await axios.post('/api/bond/buy', data);
        return response.data;
    } catch (error) {
        throw error.response?.data || { msg: '购买失败' };
    }
};

/**
 * 售出债券
 * @param {Object} data - 售出数据
 * @returns {Promise<Object>}
 */
export const $sellBond = async (data) => {
    try {
        const response = await axios.post('/api/bond/sell', data);
        return response.data;
    } catch (error) {
        throw error.response?.data || { msg: '售出失败' };
    }
};